<?php

namespace server;

use GatewayWorker\Lib\Gateway;
use plugin\webman\gateway\Events;


class Worker extends Events
{


    public static function onWebSocketConnect($client_id, $data)
    {

        if (isset($data["get"]["token"])) {
            $token = $data["get"]["token"];//获取token
            $info = base64_decode($token);//解密
            $infos = json_decode($info, true);
            if (isset($infos["user_id"])) {
                $user_id = $infos["user_id"];
                //检测用户是否连接上了websocket 如果已经有设备连接上了则不允许再次连接
                if (Gateway::isUidOnline($user_id)) {
                    //断开此客户端连接
                    Gateway::closeClient($client_id);
                }

                //如果格式正确判断token是否过期24小时
                if ($infos["u_tm"] > time() - 60 * 60 * 24) {
                    var_dump("用户连接上了");
                    //有效后绑定uid
                    Gateway::bindUid($client_id, $user_id);
                } else {
                    //过期断开
                    var_dump("token已过期");
                    //断开此客户端连接
                    Gateway::closeClient($client_id);
                }
            } else {
                var_dump("2参数错误");
                //断开此客户端连接
                Gateway::closeClient($client_id);
            }

        } else {
            var_dump("参数错误");
            //断开此客户端连接
            Gateway::closeClient($client_id);
        }

    }

    public static function onMessage($client_id, $message)
    {

        $type = $message['type'] ?? null;
        switch ($type){
            case 'logon':
                // 每2.5秒执行一次
                var_dump('发送结果');
                Gateway::sendToClient($client_id, "receive message $message");
                break;
            case 'create':
                var_dump('销毁定时器');
                break;
            default:
                var_dump('来自客户端的心态包');
                break;
        }


    }

    public static function onClose($client_id)
    {
        // Client close
        var_dump("关闭连接");
    }


}